package 力扣日常刷题.木22一月.第15天0127;

/**
 * @author 帅小伙
 * @date 2022/1/27
 * @description https://leetcode-cn.com/problems/sum-of-absolute-differences-in-a-sorted-array/
 * 输入：nums = [2,3,5]
 * 输出：[4,3,5]
 * 解释：假设数组下标从 0 开始，那么
 * result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4，
 * result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3，
 * result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5。
 */
public class Demo11差分有序数组中差绝对值之和 {


    public int[] solution(int[] nums) {
        int n = nums.length;
        int[] greed = new int[n];
        int l = 0, r = 0;
        for (int i = 0; i < n; i++) {
            r += nums[i];
        }
        greed[0] = r - nums[0] * n;

        for (int i = 1; i < nums.length; i++) {
            l += nums[i-1];
            r -= nums[i-1];
            // 右和 - 当前值*(i - n)   当前值*i - 左和   )
            greed[i] = (r - nums[i] * (n-i) ) + (nums[i] * i - l);
        }
        return greed;
    }


}
